﻿// // ******************************************************************
// //       /\ /|       @file       AiConfigCommandHandler.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2024-11-10 15:11
// //    *(__\_\        @Copyright  Copyright (c) , 2024-11-07 19:11 Await
// // ******************************************************************

using AutomaticSubtitles.Contracts.Dto;
using AutomaticSubtitles.Service.Application.AiConfig.Commands;
using AutomaticSubtitles.Service.Application.AiConfig.Queries;
using AutomaticSubtitles.Service.DataAccess.Model;
using AutomaticSubtitles.Service.Domain.Config;

namespace AutomaticSubtitles.Service.Application.AiConfig;

public class AiConfigCommandHandler(IAiConfigDataRepository repository) : BaseAutoService
{
    [EventHandler]
    public async Task Handle(AddAiConfigCommand command)
    {
        var countAsync = await repository.GetCountAsync(x => x.Name == command.data.name);
        if (countAsync > 0)
            throw new ArgumentException(ReturnMessage(Repeat));

        var autoAiconfig = command.data.MapTo<Auto_Aiconfig>();
        autoAiconfig.SetId(BasicsHelper.GetId());
        await repository.AddAsync(autoAiconfig);
        command.Result = 1;
    }


    [EventHandler]
    public async Task Handle(DeleteAiConfigCommand command)
    {
        var data = await repository.FindAsync(x => x.Id == command.id) ?? throw new ArgumentException(ReturnMessage(NoExistent));
        await repository.RemoveAsync(data);
        command.Result = 1;
    }

    [EventHandler]
    public async Task Handle(UpdateAiConfigCommand command)
    {
        if (await repository.GetCountAsync(x => x.Id != command.data.id && x.Name == command.data.name) > 0) throw new ArgumentException(ReturnMessage(Repeat));
        var data = await repository.FindAsync(x => x.Id == command.data.id)
                   ?? throw new ArgumentException(ReturnMessage(Repeat));
        data.Name = command.data.name;
        data.Token = command.data.token;
        data.Type = command.data.type;
        data.Url = command.data.url;
        data.MaxLength = command.data.maxLength;
        await repository.UpdateAsync(data);
        command.Result = 1;
    }

    [EventHandler]
    public async Task Handle(GetListAiConfigQuery command)
    {
        var autoAiconfigs = await repository.GetListAsync();
        command.Result = autoAiconfigs.MapToList<AiConfigDto>();
    }
}